package com.victor.controller.app;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.LookThings;
import com.victor.service.LookThingsService;
import com.victor.utils.Msg;
import com.victor.utils.photo_compare.ImgSimilarity;

/**
 * 见物识别
 * 
 * @author 
 *
 */
@RestController
@RequestMapping("lookthings")
public class LookThingsController {
	@Autowired
	private LookThingsService lookThingsService;
	@Autowired
	private HttpSession session;

	/**
	 * 见物识别
	 * 
	 * @param photo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/compare")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Msg lookThings(String photo) throws IOException {

		List<LookThings> list = lookThingsService.getAll();
		HashMap map = new HashMap();
		Double temp = 0.0;

		String filePath = session.getServletContext().getRealPath("/");
		File file = new File(filePath + photo);
		int[] fileint = ImgSimilarity.getImgFinger(file);

		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				try {

					double similarity = ImgSimilarity.getSimilarity(fileint, stringConvertInt(list.get(i).getPixels()));
					if (temp < similarity) {
						temp = similarity;
						map.put("path", list.get(i));
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return Msg.success().add("path", map.get("path"));

	}

	private int[] stringConvertInt(String value) {
		int[] intArr = new int[0];

		String[] valueArr = value.split(",");
		intArr = new int[valueArr.length];
		for (int i = 0; i < valueArr.length; i++) {
			intArr[i] = Integer.parseInt(valueArr[i]);
		}

		return intArr;
	}

}
